package com.foton.servletdemo.servlet;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author RenPu
 * @Date 2023/3/15 17:18
 * @Version 1.0
 * @Description: servlet3.0之后，引入了俩大特性进行：1：异步处理，2：注解避免了繁杂的web.xml的配置
 *               servlet的异步使用如下案例：
 **/
@WebServlet(value = "/test2",asyncSupported = true)
public class ServletSyncTwo extends HttpServlet {

    private static ThreadPoolExecutor threadPoolExecutor=new ThreadPoolExecutor(100,200,500L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<>(500));



    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("当前线程为：：："+Thread.currentThread().getName());
        AsyncContext async = req.startAsync();
        threadPoolExecutor.submit(()->{
            new DoSomething().run();
            try {
                async.getResponse().getWriter().write("OK get a Reponse ;;;;;;;");
            } catch (IOException e) {
                e.printStackTrace();
            }
            async.complete();  //返回一个正确的结果
        });

//
//        async.start(()->{
//            new DoSomething().run();
//            try {
//                async.getResponse().getWriter().write("OK get a Reponse ;;;;;;;");
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        async.complete();
//        });

    }
}
